/*
 * Copyright (c) 2020. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.evenmo.string;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * This is Description reetrantLock重入锁demo
 *
 * @author moyongjun
 * @date 2020/01/03
 */
public class Thread_reetrantLock {

      Lock lock= new ReentrantLock();

     public void m1(){
         //加锁
         lock.lock();

         //同步时要执行的代码
         try {
             for (int i = 0; i < 10; i++) {
                 System.out.println(i);
                 TimeUnit.SECONDS.sleep(1);
             }
         }catch (Exception e){
             e.printStackTrace();
         }finally {
             System.out.println(Thread.currentThread().getName() + "执行完毕");
             //释放锁
             System.out.println("reetrantLock手动释放锁！！！");

             lock.unlock();
         }
     }

     public void m2(){

         lock.lock();


         System.out.println("m2方法代码！！！");

         System.out.println(Thread.currentThread().getName() + "执行完毕");

         lock.unlock();
     }


    public static void main(String[] args) {

         Thread_reetrantLock tr= new Thread_reetrantLock();

         new Thread(tr::m1,"打印0到9线程").start();

         try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(tr::m2,"其他线程").start();
    }
}
